<template>
    <div class="form-group">
        <label>字体配置</label>
        <div class="font-config-group">
            <div class="font-selection">
                <select v-model="selectedFont" class="font-select" @change="applyFont">
                    <option value="">选择字体</option>
                    <option v-for="font in systemFonts" :key="font" :value="font">{{ font }}</option>
                </select>
                <button class="secondary-button" @click="loadSystemFonts" :disabled="isLoading">
                    {{ isLoading ? '加载中...' : '刷新字体列表' }}
                </button>
            </div>
            <div class="font-controls">
                <div class="font-size-control">
                    <label for="fontSize">字体大小</label>
                    <div class="range-input-group">
                        <input type="range" id="fontSize" min="8" max="72" step="1" v-model="fontSize"
                            @input="applyFont" class="range-slider">
                        <span class="range-value">{{ fontSize }}px</span>
                    </div>
                </div>
                <div class="font-weight-control">
                    <label for="fontWeight">字体粗细</label>
                    <select v-model="fontWeight" class="font-weight-select" @change="applyFont">
                        <option value="normal">正常</option>
                        <option value="bold">粗体</option>
                        <option value="lighter">细体</option>
                        <option value="100">100</option>
                        <option value="200">200</option>
                        <option value="300">300</option>
                        <option value="400">400</option>
                        <option value="500">500</option>
                        <option value="600">600</option>
                        <option value="700">700</option>
                        <option value="800">800</option>
                        <option value="900">900</option>
                    </select>
                </div>
            </div>
            <div class="font-actions">
                <button class="primary-button" @click="applyFont">应用字体</button>
                <button class="secondary-button" @click="resetFont">重置字体</button>
            </div>
            <!-- <div class="font-info" v-if="systemFonts.length > 0">
                <small>已检测到 {{ systemFonts.length }} 个系统字体</small>
            </div> -->
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { inject } from 'vue';

// Emits
const emit = defineEmits(['apply-font', 'reset-font'])
const fontConfig = inject('fontConfig');

// 响应式数据
const systemFonts = ref([])
const selectedFont = ref('pingFang SC')
const fontWeight = ref('normal')
const isLoading = ref(false)
const fontSize = ref(16);

// 加载系统字体列表
async function loadSystemFonts() {
    try {
        isLoading.value = true

        // 首先尝试使用Electron API获取真正的系统字体
        if (window.api && window.api.getSystemFonts) {
            // console.log('正在从系统获取字体列表...')
            const fonts = await window.api.getSystemFonts()
            if (fonts && fonts.length > 0) {
                systemFonts.value = fonts
                // console.log('成功获取系统字体:', fonts.length, '个')
                return
            }
        }

        // 如果Electron API不可用，回退到Web API检测
        console.log('回退到Web API字体检测...')
        await loadFontsWithWebAPI()

    } catch (error) {
        console.error('加载系统字体失败:', error)
        // 提供备用字体列表
        systemFonts.value = [
            'Arial', 'Times New Roman', 'Helvetica', 'Georgia', 'Verdana',
            'Microsoft YaHei', '微软雅黑', 'SimSun', '宋体', 'SimHei', '黑体',
            'system-ui', 'sans-serif', 'serif', 'monospace'
        ].sort()
    } finally {
        isLoading.value = false
    }
}

// 使用Web API检测字体（备用方法）
async function loadFontsWithWebAPI() {
    // 检测字体是否可用的函数
    function isFontAvailable(fontName) {
        const canvas = document.createElement('canvas')
        const context = canvas.getContext('2d')

        // 使用默认字体绘制文本
        context.font = '12px monospace'
        const defaultWidth = context.measureText('测试字体 Test Font').width

        // 使用测试字体绘制文本
        context.font = `12px "${fontName}", monospace`
        const testWidth = context.measureText('测试字体 Test Font').width

        // 如果宽度不同，说明字体可用
        return defaultWidth !== testWidth
    }

    // 常见的系统字体列表
    const commonFonts = [
        // 中文字体
        'Microsoft YaHei', '微软雅黑', 'SimSun', '宋体', 'SimHei', '黑体',
        'KaiTi', '楷体', 'FangSong', '仿宋', 'NSimSun', '新宋体',
        'Microsoft JhengHei', '微软正黑体', 'PMingLiU', '新细明体',
        'DFKai-SB', '标楷体', 'MingLiU', '细明体',

        // 英文字体
        'Arial', 'Times New Roman', 'Helvetica', 'Georgia', 'Verdana',
        'Tahoma', 'Trebuchet MS', 'Arial Black', 'Impact', 'Comic Sans MS',
        'Courier New', 'Lucida Console', 'Palatino Linotype', 'Book Antiqua',
        'Lucida Sans Unicode', 'MS Sans Serif', 'MS Serif', 'Calibri', 'Cambria',

        // 等宽字体
        'Consolas', 'Monaco', 'Menlo', 'Source Code Pro', 'Fira Code',
        'JetBrains Mono', 'Cascadia Code', 'Ubuntu Mono',

        // 系统字体
        'system-ui', '-apple-system', 'BlinkMacSystemFont', 'Segoe UI',
        'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Helvetica Neue'
    ]

    const availableFonts = []

    // 检测每个字体
    for (const font of commonFonts) {
        if (isFontAvailable(font)) {
            availableFonts.push(font)
        }
    }

    // 尝试使用Font Loading API获取更多字体
    if ('fonts' in document) {
        try {
            await document.fonts.ready
            const fontFaceSet = document.fonts
            for (const fontFace of fontFaceSet) {
                if (fontFace.family && !availableFonts.includes(fontFace.family)) {
                    availableFonts.push(fontFace.family)
                }
            }
        } catch (error) {
            console.log('Font Loading API 不可用:', error)
        }
    }

    // 去重并排序
    systemFonts.value = [...new Set(availableFonts)].sort()
    console.log('Web API检测到的字体:', systemFonts.value.length, '个')
}

// 应用字体
function applyFont() {
    // const fontConfig = {
    //     family: selectedFont.value,
    //     size: fontSize.value,
    //     weight: fontWeight.value
    // }
    fontConfig.family = selectedFont.value;
    fontConfig.size = fontSize.value;
    fontConfig.weight = fontWeight.value;
    emit('apply-font', fontConfig)
}

// 重置字体
function resetFont() {
    selectedFont.value = 'pingFang SC'
    fontSize.value = 16
    fontWeight.value = 'normal'
    fontConfig.family = 'pingFang SC';
    fontConfig.size = 16;
    fontConfig.weight = 'normal';
    emit('reset-font')
}

// 组件挂载时加载字体
onMounted(() => {
    loadSystemFonts()
})

// 暴露数据
defineExpose({
    systemFonts,
    selectedFont,
    fontSize,
    fontWeight
})
</script>

<style scoped>
.form-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.form-group label {
    font-size: 14px;
    color: #333;
    font-weight: 500;
}

.font-config-group {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.font-selection {
    display: flex;
    gap: 8px;
    align-items: center;
}

.font-select {
    padding: 6px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: #fff;
    font-size: 14px;
    width: 100%;
}

.font-controls {
    display: flex;
    gap: 16px;
    align-items: center;
}

.font-size-control,
.font-weight-control {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.font-size-control label,
.font-weight-control label {
    font-size: 12px;
    color: #666;
}

.font-weight-select {
    padding: 4px;
    border: 1px solid #ddd;
    border-radius: 4px;
    background-color: #fff;
    font-size: 12px;
    min-width: 80px;
}

.font-actions {
    display: flex;
    gap: 8px;
}

.range-input-group {
    display: flex;
    gap: 12px;
    align-items: center;
}

.range-slider {
    flex: 1;
    height: 6px;
    -webkit-appearance: none;
    background: #e1e1e1;
    border-radius: 3px;
    outline: none;
}

.range-slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    width: 16px;
    height: 16px;
    background: #1890ff;
    border-radius: 50%;
    cursor: pointer;
}

.range-value {
    min-width: 40px;
    font-size: 14px;
    color: #666;
}

.primary-button,
.secondary-button {
    flex-shrink: 0;
    padding: 6px 12px;
    border-radius: 4px;
    border: none;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s;
}

.primary-button {
    background-color: #1890ff;
    color: white;
}

.primary-button:hover {
    background-color: #40a9ff;
}

.secondary-button {
    background-color: #f0f0f0;
    color: #333;
}

.secondary-button:hover {
    background-color: #d9d9d9;
}

.font-info {
    margin-top: 8px;
    padding: 4px 8px;
    background-color: #f0f8ff;
    border-radius: 4px;
    border-left: 3px solid #1890ff;
}

.font-info small {
    color: #666;
    font-size: 12px;
}

.secondary-button:disabled {
    background-color: #f5f5f5;
    color: #999;
    cursor: not-allowed;
}
</style>